package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDLocation;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CanYinAdapter;
import com.example.administrator.yanfoxconn.adapter.CanYinSecondAdapter;
import com.example.administrator.yanfoxconn.adapter.GBYueNanCheckAdapter;
import com.example.administrator.yanfoxconn.adapter.ZhiyinshuiCheckAdapter;
import com.example.administrator.yanfoxconn.bean.CanYinInfo;
import com.example.administrator.yanfoxconn.bean.ZhiyinshuiCheckMsg;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Song
 * on 2020/7/21
 * Description：地點、車輛 帶點檢項的巡檢維護界面
 */
public class CanYinSecondActivityNew extends BaseActivity implements View.OnClickListener{

    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息
    private final int MESSAGE_JUMP = 4;//跳轉維護界面
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_CHECK = 6;
    private final int MESSAGE_SET_PHOTO = 0;//獲取圖片
    private final int MESSAGE_GET_PHOTO_FAIL = 1;//獲取圖片


    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_right)
    Button btnUp;//提交
    @BindView(R.id.rv_option)
    RecyclerView rvOption;//點檢項目列表

    private String flag,mainName;//主類別，mainName
    private String[] qrResult;//二維碼內含結果
    private CanYinSecondAdapter canYinSecondAdapter;//點檢列表適配器
    private HashMap<Integer, ArrayList<String>> photoList = new HashMap<>();//用户存储条目的选择状态
    private HashMap<Integer, String> conList = new HashMap<>();//用户存储条目的选择状态
    private HashMap<Integer, String> exList = new HashMap<>();//用户人數存储条目的
    private String url;//請求地址
    private String result;//請求返回結果
    private String type;//類型
    private List<CanYinInfo> canYinInfos,photoInfos;
    private boolean isClicked = true;//判斷是否點擊
    private int param1,param2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canyin_second);

        ButterKnife.bind(this);
        tvTitle.setText("巡檢界面");
        btnUp.setText("提交");
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setOnClickListener(this);
        btnBack.setOnClickListener(this);

        qrResult = getIntent().getStringExtra("result").split(",");
        flag = getIntent().getStringExtra("flag");
        type = FoxContext.getInstance().getType();
        mainName = getIntent().getStringExtra("mainName");
        getItem( flag);
    }

    /**
     * 獲取點檢項目
     * @param flag
     */
    public void getItem( String flag) {
        showDialog();
        url = Constants.HTTP_CY_SECOND_TYPE + "?flag=" + flag;


        Log.e("-----", "fff--" + url);
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                Log.e("---fff--result----", result.toString());
                if (result != null) {

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
//
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        canYinInfos = new ArrayList<CanYinInfo>();

                        for (JsonElement type : array) {
                            CanYinInfo humi = gson.fromJson(type, CanYinInfo.class);
                            canYinInfos.add(humi);

                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_CHECK;
//                        message.obj = messageList;
                        mHandler.sendMessage(message);
                    } else {

                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString() + ",請聯繫部門管理人員維護資料!";
                        mHandler.sendMessage(message);
                    }
                } else {
                    ToastUtils.showShort(CanYinSecondActivityNew.this, "請求不成功");
                }

            }
        }.start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_title_right:
                if (canYinInfos != null) {

                        if (isClicked){
                            check();
                            isClicked = false;
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    isClicked = true;
                                }
                            }, 2000);
                        }else{
                            ToastUtils.showShort(CanYinSecondActivityNew.this,R.string.multiple_click);
                        }
                    }
                break;
        }
    }
    //提交前檢查
    private void check() {

        url = Constants.HTTP_CY_PHOTO_UPLOAD; //此處寫上自己的URL

        JsonObject object = new JsonObject();
        HashMap<Integer, ArrayList<String>> imagePathsMap; //存放圖片地址的map
        HashMap<Integer, String> etMap;//存放editText值的map
        BDLocation location = FoxContext.getInstance().getLocation();
        if (location == null || location.getLongitude() == 0.0 || location.getLatitude() == 0.0) {
            ToastUtils.showLong(this, "位置信息獲取失敗請稍後或移動后重試!");
        }
        imagePathsMap = CanYinSecondAdapter.getImagePathsMap();
        etMap = CanYinSecondAdapter.getEtLists();
        JsonArray array = new JsonArray();


        for (int i = 0; i < canYinInfos.size(); i++) {
            JsonObject jsonObject = new JsonObject();

            jsonObject.addProperty("r_id", qrResult[0]);
            jsonObject.addProperty("r_name",  qrResult[1]);
            jsonObject.addProperty("r_main_type", mainName);
            jsonObject.addProperty("r_second_type", canYinInfos.get(i).getName());
            jsonObject.addProperty("r_creator", FoxContext.getInstance().getName());
            if (flag.equals("SJ1")||flag.equals("SJ2")||flag.equals("SJ3")||flag.equals("SJ4")){

                jsonObject.addProperty("r_content", etMap.get(i));
            }else{
            jsonObject.addProperty("r_content", "");
            }


            JsonArray photoArray = new JsonArray();
            if(photoList.get(i) != null && photoList.get(i).size()!=0){
                for (int k = 0; k < photoList.get(i).size(); k++) {
                    final String pic_path = photoList.get(i).get(k);
                    JsonObject jsonObject1 = new JsonObject();
                    jsonObject1.addProperty("file", pic_path);
                    photoArray.add(jsonObject1);
                }
            }
            if (imagePathsMap.get(i) != null && imagePathsMap.get(i).size()!=0) {
                for (int k = 0; k < imagePathsMap.get(i).size(); k++) {
                    final String pic_path = imagePathsMap.get(i).get(k);
                    //Log.e("------pic_path-------", pic_path);
                    String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                    String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+k+ ".jpg";
                    //Log.e("------_path-------", _path);
                    final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 50);
                    //Log.e("----compressImage---", compressImage);
                    String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
                    //Log.e("----picBase64Code----", "===="+ picBase64Code);
                    JsonObject jsonObject1 = new JsonObject();
                    jsonObject1.addProperty("file", picBase64Code);
                    photoArray.add(jsonObject1);
                }
            }
            jsonObject.add("photo", photoArray);
            array.add(jsonObject);
        }
        object.add("info", array);

        Log.e("---------", "==fff===" + object);
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("---------", "==fff===" + url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else {
                            //Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    } else {
                        Message message = new Message();
                        message.what = MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    FileUtil.deletePhotos(CanYinSecondActivityNew.this);
                }
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(CanYinSecondActivityNew.this, R.string.net_mistake);
                    break;
                case MESSAGE_TOAST:
                    ToastUtils.showShort(CanYinSecondActivityNew.this, msg.obj.toString());
                    finish();
                    break;
                case MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(), MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
                    break;
                case MESSAGE_SET_CHECK://點檢項列表賦值
                    if (canYinInfos != null) {

                        getPhotoList();

                    } else {
                        ToastUtils.showShort(CanYinSecondActivityNew.this, "沒有數據!");
                    }

                    break;
                case MESSAGE_SET_PHOTO:
                    int num=0;
                    List<String> photos;
                    String content = null;
                    for (int j=0;j<canYinInfos.size();j++){
                        photos = new ArrayList<>();
                        for (int i=0;i<photoInfos.size();i++){
                            if (canYinInfos.get(j).getName().equals(photoInfos.get(i).getR_second_type())){
                              photos.add(photoInfos.get(i).getR_file());
                              content=photoInfos.get(i).getR_content();
                            }
                        }
                        conList.put(num,content);
                        photoList.put(num, (ArrayList<String>) photos);
                        num++;
                    }
                    LinearLayoutManager layoutManager = new LinearLayoutManager(CanYinSecondActivityNew.this);
                    rvOption.setLayoutManager(layoutManager);
                    rvOption.setItemViewCacheSize(500);
                    canYinSecondAdapter = new CanYinSecondAdapter(CanYinSecondActivityNew.this, canYinInfos,flag,photoList,"Y",conList);
                    rvOption.setAdapter(canYinSecondAdapter);
                    canYinSecondAdapter.setOnClickListener(new CanYinSecondAdapter.OnClickListener() {
                        @Override
                        public void onclick(int paramInt1, int paramInt2, View view) {
                            int[] location = new int[2];
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                Rect frame = new Rect();
                                getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
                                int statusBarHeight = frame.top;

                                view.getLocationOnScreen(location);
                                location[1] += 0;
                            } else {
                                view.getLocationOnScreen(location);
                            }
                            view.invalidate();
                            int width = view.getWidth();
                            int height = view.getHeight();

                            Intent intent = new Intent(CanYinSecondActivityNew.this, BigImageActivity.class);
                            Bundle b = new Bundle();
                            b.putString(BigImageActivity.QR_IMAGE_URL, photoList.get(paramInt1).get(paramInt2));
                            intent.putExtras(b);
                                intent.putExtra(BigImageActivity.PHOTO_SELECT_POSITION,333);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_X_TAG, location[0]);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_Y_TAG, location[1]);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_W_TAG, width);
                            intent.putExtra(BigImageActivity.PHOTO_SELECT_H_TAG, height);
//                            startActivity(intent);
                            startActivityForResult(intent,0);
                            param1=paramInt1;
                            param2=paramInt2;
                            overridePendingTransition(0, 0);
                        }
                    });

                    break;
                case MESSAGE_GET_PHOTO_FAIL:
                    LinearLayoutManager layoutManager1 = new LinearLayoutManager(CanYinSecondActivityNew.this);
                    rvOption.setLayoutManager(layoutManager1);
                    rvOption.setItemViewCacheSize(500);
                    canYinSecondAdapter = new CanYinSecondAdapter(CanYinSecondActivityNew.this, canYinInfos,flag,"N");
                    rvOption.setAdapter(canYinSecondAdapter);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void getPhotoList(){
        new Thread() {
            @Override
            public void run() {
                String flagname=URLEncoder.encode(URLEncoder.encode(qrResult[1]));
                String name=URLEncoder.encode(URLEncoder.encode(mainName));
                String url2 = Constants.HTTP_CY_PHOTO_GET + "?flag=" +name +"&name="+flagname;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        photoInfos = new ArrayList<CanYinInfo>();

                        for (JsonElement type : array) {
                            CanYinInfo humi = gson.fromJson(type, CanYinInfo.class);
                            photoInfos.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_PHOTO;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    }else{
                        Message message = new Message();
                        message.what = MESSAGE_GET_PHOTO_FAIL;
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();

    }

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type == MESSAGE_TOAST) {
                            finish();
                        } else if (type == MESSAGE_UP) {
                            check();
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub

//                        if (type==MESSAGE_TOAST){
//                            finish();
//                        }else if(type==MESSAGE_UP){
//                            check();
//                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void worningAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type == MESSAGE_TOAST) {
                            finish();
                        } else if (type == MESSAGE_JUMP) {
                            ToastUtils.showShort(CanYinSecondActivityNew.this, "跳轉異常界面!");
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub

//                        if (type==MESSAGE_TOAST){
//                            finish();
//                        }else if(type==MESSAGE_UP){
//                            check();
//                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;
    private static final int REQUEST_DEL_CODE = 33;
    private ImageCaptureManager captureManager; // 相机拍照处理类

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
// 选择照片
                case REQUEST_DEL_CODE:
                    Log.e("==========", "33===" + canYinSecondAdapter.getPosition());
                    break;
                // 选择照片
                case REQUEST_CAMERA_CODE:
                        Log.e("==========", "Picker===" + canYinSecondAdapter.getPosition());
                    canYinSecondAdapter.loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), canYinSecondAdapter.getPosition());
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    canYinSecondAdapter.loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT), canYinSecondAdapter.getPosition());
                    Log.e("==========", "Preview===" + canYinSecondAdapter.getPosition());
                    break;// 预览

                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());

                        canYinSecondAdapter.loadAdpater(paths, canYinSecondAdapter.getPosition());
                        Log.e("==========", paths.get(1));}

                    break;
            }
        } else {
            switch (resultCode) {
                case 33:
                    Log.e("==========", "canYinSecondAdapter.notifyDataSetChanged();===");
                    photoList.get(param1).remove(param2);
                    Log.e("==========", "canYinSecondAdapter.notifyDataSetChanged();===");
                    canYinSecondAdapter.notifyDataSetChanged();
                    break;
                case 44:

                    break;
            }

            }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        CanYinSecondAdapter.getImagePathsMap().clear();
//        CanYinSecondAdapter.getEtMap().clear();
//        CanYinSecondAdapter.getEtCheckMap().clear();
    }


}
